from tkinter import *
import os
from moviepy.editor import AudioFileClip
import os

#打包问题解决：https://zhuanlan.zhihu.com/p/307505292

def gui():
    # 第1步，实例化object，建立窗口window
    window=Tk()

    # 第2步，给窗口的可视化起名字
    window.title('视频提取音频-作者：blueSky')

    window.geometry('530x150')  # 这里的乘是小x

    # 桌面
    desktop=os.path.join(os.path.expanduser("~"), 'Desktop')

    strvar=StringVar()
    strvar.set(desktop)

    l1=Label(window, text="读视频返回mp3")

    addr = StringVar(value='D:\\win-videos\\TestVideo\\test.mp4')
    e1=Entry(window, show=None, width=50,textvariable=addr)

    # l2=Label(window, text="合并后文件的存放路径")
    # e2=Entry(window, show=None, width=50, textvariable=strvar)

    def insert_point():  # 在鼠标焦点处插入输入内容
        # 扫描excel的目录路径
        e1value=e1.get()
        work(e1value)



    # 第6步，创建并放置两个按钮分别触发两种情况
    btn1=Button(window, text='开始执行', width=10,
                height=2, command=insert_point)




    t=Text(window, height=3)
    l1.grid(row=1, column=1, sticky=E)
    e1.grid(row=1, column=2, sticky=E)
    # l2.grid(row=2, column=1, sticky=E)
    # e2.grid(row=2, column=2, sticky=E)
    btn1.grid(row=4, column=1, sticky=E)

    # 第8步，主窗口循环显示
    window.mainloop()



#生成MP3文件，MP3文件会放到视频目录下的mp3Dir文件夹下
def getMP3(filePath):
    print(filePath)
    #文件名，不带后缀
    filename = os.path.basename(filePath).split(".")[0]+ ".mp3"
    dirName = os.path.dirname(filePath)

    mp3DirName = os.path.join(dirName,"mp3Dir")
    if not os.path.exists(mp3DirName):
        os.makedirs(mp3DirName)
    mp3 = os.path.join(mp3DirName,filename)

    my_audio_clip = AudioFileClip(filePath)
    my_audio_clip.write_audiofile(mp3)



# 返回文件路径list
def findAllFile(base):
    for root, ds, fs in os.walk(base):
        for f in fs:
            if f.endswith('.mp4'):
                fullname = os.path.join(root, f)
                yield fullname


def work(path):
    if os.path.isdir(path):
        files = findAllFile(path)
        for file in files:
            getMP3(file)
    if os.path.isfile(path):
        file = path
        getMP3(file)
if __name__ == '__main__':
    gui()
